package com.hualude.roadsign.repository;

import com.hualude.roadsign.dto.DTRequestDto;
import com.hualude.roadsign.dto.FaultCountDto;
import com.hualude.roadsign.dto.MonitorDto;
import com.hualude.roadsign.dto.MonitorFaultDto;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

import static com.hualude.roadsign.service.impl.CountServiceImpl.convertParams;

/**
 * Created by ding on 2017/9/22.
 */
public class MonitorFaultCountRepositoryImpl {

    @PersistenceContext
    private EntityManager em;

    public List<String> getDealCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select m.MonitorMaintenanceTime from tb_monitor_fault m,tb_user u where m.MonitorMaintenanceStatus = 2 and " +
                "(m.MonitorMaintenanceTime between '" + year + "' and '" + yearNext + "') and m.MonitorMaintainerId = u.userId and u.orgId in (" + orgIds + ")";
        Query query = em.createNativeQuery(hql);
        List<String> times = query.getResultList();
        return times;
    }

    public List<String> getReportCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select s.MonitorFaultTime from tb_monitor_fault s where " +
                "(s.MonitorFaultTime between '" + year + "' and '" + yearNext + "') and  (s.MonitorOrgId in (" + orgIds + ") or " +
                "s.MonitorMainOrgId in (" + orgIds + "))";
        Query query = em.createNativeQuery(hql);
        List<String> times = query.getResultList();
        return times;
    }

    public List<FaultCountDto> getExpenseCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select m.MonitorMaintenanceTime AS maintenanceTime,m.MonitorMoney AS repairAmount from tb_monitor_fault m,tb_user u where " +
                "(m.MonitorMaintenanceTime between '" + year + "' and '" + yearNext + "') and m.MonitorMaintainerId = u.userId and u.orgId in (" + orgIds + ")";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(FaultCountDto.class));
        List<FaultCountDto> maintenanceDtos = query.getResultList();
        return maintenanceDtos;
    }

    public List<MonitorFaultDto> getFault4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select f.MonitorFaultId,f.MonitorId,f.MonitorFaultPhoto,p.MonitorPhoto,f.MonitorFaultLevel,f.MonitorCheck,f.MonitorMainCheck,\n" +
                "f.MonitorFaultTime,f.MonitorCheckTime,o.OrgName AS monitorOrgName,o2.orgName as monitorMainOrgName,p.MonitorPeriod," +
                " p.MonitorRoadName,p.MonitorStartRoad,p.MonitorEndRoad,p.monitorSize,p.monitorServiceLife,p.monitorPosition,p.monitorPoleShape,p.monitorDirection,\n" +
                "p.MonitorArea,p.MonitorCity,p.MonitorProvince,u.UserName AS monitorCreatorName\n" +
                "from tb_monitor_fault f,tb_org o,tb_org o2,tb_monitor p,tb_user u\n" +
                "where f.MonitorOrgId = o.OrgId and p.MonitorMainOrgId=o2.orgId and f.MonitorId = p.MonitorId  AND\n" +
                "f.MonitorFaultCreatorId = u.UserId";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and f.MonitorFaultTime between '" + dateStr[0] + "' and '" + dateStr[1]+1 + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (f.MonitorOrgId IN (" + orgIds + ") or " +
                    "f.MonitorMainOrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY f.MonitorFaultTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(MonitorFaultDto.class));
        List<MonitorFaultDto> roadpoleDto = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return roadpoleDto;
    }

    public Integer getFaultCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select count(*) from tb_monitor_fault f,tb_org o WHERE f.MonitorOrgId= o.OrgId";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and f.MonitorFaultTime between '" + dateStr[0] + "' and '" + dateStr[1]+1 + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (f.MonitorOrgId IN (" + orgIds + ") or " +
                    "f.MonitorMainOrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public List<MonitorFaultDto> getDevice4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds, Integer userId) throws Exception {
        String hql = "select m.MonitorFaultId,m.MonitorFaultPhoto,m.MonitorMaintenancePhoto,m.MonitorMaintenanceStatus,m.MonitorMaintenanceTime,MonitorMoney,\n" +
                "o.OrgName AS monitorOrgName,m.MonitorId,s.MonitorRoadName,s.MonitorEndRoad,s.MonitorStartRoad,s.MonitorArea,s.monitorPosition,s.monitorPoleShape,s.monitorDirection,\n" +
                "s.MonitorCity,s.MonitorProvince,o2.orgName as monitorMainOrgName,s.MonitorPhoto,s.MonitorPeriod,u.UserName AS monitorCreatorName\n" +
                "from tb_monitor_fault m,tb_user u,tb_org o,tb_org o2,tb_monitor s \n" +
                "where m.MonitorMaintenanceStatus=2 and m.MonitorMaintainerId = u.userId and s.MonitorMainOrgId=o2.orgId\n" +
                "and u.OrgId = o.OrgId and m.MonitorId = s.MonitorId ";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and m.MonitorMaintenanceTime between '" + dateStr[0] + "' and '" + dateStr[1] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (u.OrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY m.MonitorMaintenanceTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(MonitorFaultDto.class));
        List<MonitorFaultDto> roadpoleDto = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return roadpoleDto;
    }

    public Integer getDeviceCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds, Integer userId) throws Exception {
        String hql = "select count(*) from tb_monitor_fault m,tb_user u,tb_org o,tb_org o2,tb_monitor s \n" +
        "where m.MonitorMaintenanceStatus=2 and m.MonitorMaintainerId = u.userId and s.MonitorMainOrgId=o2.orgId\n" +
                "and u.OrgId = o.OrgId and m.MonitorId = s.MonitorId ";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and m.MonitorMaintenanceTime between '" + dateStr[0] + "' and '" + dateStr[1] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (u.OrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }


    public Integer getMonitorCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select count(*) from tb_monitor where MonitorId like '%'";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        //0:省 1:市 2:区域 3:道路 4:起始路段 5:终止路段 6:主管单位 7:养护公司
        if (!sQuery[0].equals("-1")) {
            hql += " and MonitorProvince = '" + sQuery[0] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and MonitorCity = '" + sQuery[1] + "'";
        }
        if (!sQuery[2].equals("-1")) {
            hql += " and MonitorArea = '" + sQuery[2] + "'";
        }
        if (!sQuery[3].equals("-1")) {
            hql += " and MonitorRoadName ='" + sQuery[3] + "'";
        }
        if (!sQuery[4].equals("-1") && sQuery[5].equals("-1")) {
            hql += " and (MonitorStartRoad ='" + sQuery[4] + "' or MonitorEndRoad ='" + sQuery[4] + "')";
        }
        if (sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and (MonitorEndRoad ='" + sQuery[5] + "' or MonitorStartRoad ='" + sQuery[5] + "')";
        }
        if (!sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and ((MonitorStartRoad ='" + sQuery[4] + "' and MonitorEndRoad ='" + sQuery[5] + "') or" +
                    "(MonitorStartRoad = '" + sQuery[5] + "' and MonitorEndRoad = '" + sQuery[4] + "'))";
        }
        if (!sQuery[6].equals("-1")) {
            hql += " and MonitorMainOrgId = '" + sQuery[6] + "'";
        }
        if (!sQuery[7].equals("-1")) {
            hql += " and MonitorOrgId = '" + sQuery[7] + "'";
        }
        if (actor != 1) {
            hql += " and (MonitorOrgId IN (" + orgIds + ") or " +
                    "MonitorMainOrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public List<MonitorDto> getMonitor4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select m.MonitorId,m.MonitorPhoto,m.MonitorProvince,m.MonitorCity,m.MonitorArea," +
                "m.MonitorRoadName,e.OrgName as monitorMainOrgName,o.OrgName as monitorOrgName,m.MonitorLongitude," +
                "m.MonitorLatitude,m.MonitorDirection,m.MonitorPoleShape,m.MonitorSize,m.MonitorPosition," +
                "m.MonitorInstallTime,m.MonitorStartRoad,m.MonitorEndRoad,m.MonitorIsComplete from tb_monitor m " +
                "LEFT JOIN tb_org e ON m.MonitorMainOrgId = e.OrgId " +
                "LEFT JOIN tb_org o ON m.MonitorOrgId = o.OrgId " +
                "where m.MonitorId LIKE '%'";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        //0:省 1:市 2:区域 3:道路 4:起始路段 5:终止路段 6:主管单位 7:养护公司
        if (!sQuery[0].equals("-1")) {
            hql += " and MonitorProvince = '" + sQuery[0] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and MonitorCity = '" + sQuery[1] + "'";
        }
        if (!sQuery[2].equals("-1")) {
            hql += " and MonitorArea = '" + sQuery[2] + "'";
        }
        if (!sQuery[3].equals("-1")) {
            hql += " and MonitorRoadName ='" + sQuery[3] + "'";
        }
        if (!sQuery[4].equals("-1") && sQuery[5].equals("-1")) {
            hql += " and (MonitorStartRoad ='" + sQuery[4] + "' or MonitorEndRoad ='" + sQuery[4] + "')";
        }
        if (sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and (MonitorEndRoad ='" + sQuery[5] + "' or MonitorStartRoad ='" + sQuery[5] + "')";
        }
        if (!sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and ((MonitorStartRoad ='" + sQuery[4] + "' and MonitorEndRoad ='" + sQuery[5] + "') or" +
                    "(MonitorStartRoad = '" + sQuery[5] + "' and MonitorEndRoad = '" + sQuery[4] + "'))";
        }
        if (!sQuery[6].equals("-1")) {
            hql += " and MonitorMainOrgId = '" + sQuery[6] + "'";
        }
        if (!sQuery[7].equals("-1")) {
            hql += " and MonitorOrgId = '" + sQuery[7] + "'";
        }
        if (actor != 1) {
            hql += " and (MonitorOrgId IN (" + orgIds + ") or " +
                    "MonitorMainOrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY m.MonitorInstallTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(MonitorDto.class));
        List<MonitorDto> monitorDtos = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return monitorDtos;
    }

    public List<String> getProvinceName(String orgIds) throws Exception {
        String hql = "select distinct m.MonitorProvince from tb_monitor m where m.MonitorOrgId in (" + orgIds + ") or " +
                "m.MonitorMainOrgId in (" + orgIds + ")";
        hql += " order by convert(m.MonitorProvince using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> province = query.getResultList();
        return province;
    }

    public List<String> getCityName(String orgIds, String provinceName) throws Exception {
        String hql = "select distinct m.MonitorCity from tb_monitor m where (m.MonitorOrgId in (" + orgIds + ") or " +
                "m.MonitorMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and m.MonitorProvince = '" + provinceName + "'";
        }
        hql += " order by convert(m.MonitorCity using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> city = query.getResultList();
        return city;
    }

    public List<String> getAllAreaName(String orgIds, String provinceName, String cityName) throws Exception {
        String hql = "select distinct m.MonitorArea from tb_monitor m where (m.MonitorOrgId IN (" + orgIds + ")" +
                " or m.MonitorMainOrgId IN (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and m.MonitorProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and m.MonitorCity ='" + cityName + "'";
        }
        hql += " order by convert(m.MonitorArea using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> area = query.getResultList();
        return area;
    }

    public List<String> getRoadNames(String provinceName, String cityName, String areaName, String orgId, Integer actor) throws Exception {
        String hql = "select distinct m.MonitorRoadName from tb_monitor m where (m.MonitorOrgId in (" + orgId + ") or " +
                "m.MonitorMainOrgId in (" + orgId + "))";
        if (!provinceName.equals("-1")) {
            hql += " and m.MonitorProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and m.MonitorCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and m.MonitorArea = '" + areaName + "'";
        }
        hql += " order by convert(m.MonitorRoadName using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<String> getStartRoadName(String orgIds, String provinceName, String cityName, String areaName,
                                         String endRoadName, String roadName) throws Exception {
        String hql = "select distinct m.MonitorStartRoad from tb_monitor m where (m.MonitorOrgId in (" + orgIds + ") or " +
                "m.MonitorMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and m.MonitorProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and m.MonitorCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and m.MonitorArea = '" + areaName + "'";
        }
        if (!endRoadName.equals("-1")) {
            hql += " and m.MonitorEndRoad = '" + endRoadName + "'";
        }
        if (!roadName.equals("-1")) {
            hql += " and m.MonitorRoadName = '" + roadName + "'";
        }
        hql += " order by convert(m.MonitorStartRoad using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<String> getEndRoadName(String orgIds, String startRoad, String provinceName, String cityName,
                                       String areaName, String roadName) throws Exception {
        String hql = "select distinct m.MonitorEndRoad from tb_monitor m where (m.MonitorOrgId in (" + orgIds + ") or " +
                "m.MonitorMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and m.MonitorProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and m.MonitorCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and m.MonitorArea = '" + areaName + "'";
        }
        if (!startRoad.equals("-1")) {
            hql += " and m.MonitorStartRoad = '" + startRoad + "'";
        }
        if (!roadName.equals("-1")) {
            hql += " and m.MonitorRoadName = '" + roadName + "'";
        }
        hql += " order by convert(m.MonitorEndRoad using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<Integer> getMonitorTypeCounts(String orgIds, String time, String province, String city, String area, String road) throws Exception {
        String[] timeLimit = {"", ""};
        timeLimit = time.split(" - ");
        String hql = "select m.MonitorPoleShape from tb_monitor m  where (m.MonitorOrgId in (" + orgIds + ") or " +
                "m.MonitorMainOrgId in (" + orgIds + ")) AND (m.MonitorInstallTime between '" + timeLimit[0] + "' and '" + timeLimit[1] + "') " +
                " and m.MonitorProvince like '%" + province + "%' and m.MonitorCity like '%" + city + "%' " +
                " and m.MonitorArea like '%" + area + "%' and m.MonitorRoadName like '%" + road + "%'   ORDER BY m.MonitorPoleShape";
        Query query = em.createNativeQuery(hql);
        List<Integer> counts = query.getResultList();
        return counts;
    }
}
